package com.nokia.forum.examples.racer.views;
import com.nokia.forum.examples.racer.views.components.Ball;
import com.nokia.forum.examples.racer.helpers.ImageLoader;
import com.nokia.forum.examples.racer.helpers.SimpleThread;
import com.nokia.forum.examples.racer.helpers.Engine;

import javax.microedition.lcdui.game.GameCanvas;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;
import java.util.Random;
/**
 *
 * @author tuokor
 */
public class GameView extends GameCanvas  {

    private Ball [][] ArrayOfBall;
    private int last_i=-1;
    private int last_j=-1;
    private int nMine=0;
    private int nMineAround=0;
    private boolean use_press;
    private boolean createdMineField;
    private Timer mTimer;
    private Timer raceTimer;
    private TimerTask clock;

  
    private Graphics g;
    private Pointer p;
 
    private int currentFrame = 0;
    private int lastFrame = 0;
    
    private int curRed = 0;
    private int curGreen = 0;
    private int curBlue = 0;

    
   

    private Image bg;
  
    private Image startInfo;
  
  
    private Sprite countDown;
    private Image balls;

  
    private boolean stopped = true;
   

    private Engine engine = new Engine();

  
    private SimpleThread gameLogic;
    private Thread countdownThread;

    private int pauseCounter = 0;
    private String error = "";
    private Font smallFont = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALIC, Font.SIZE_SMALL);
    private Font bigFont = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALIC, Font.SIZE_LARGE);
    public GameView() {
        super(false);
        setFullScreenMode(true);
        loadGraphics();
        createBalls();
        engine.start();
        p=null;
    }
    private void createBalls(){
        Ball ball;
        Random ran=new Random();
        int c,r;
        ArrayOfBall=new Ball[9][9];
        for(int i=0;i<9;i++)
            for(int j=0;j<9;j++)
            {
                ball=new Ball(26*i,32+26*j,balls);
                ArrayOfBall[i][j]=ball;
            }
        while(nMine<10)
        {
            c=ran.nextInt(9);
            r=ran.nextInt(9);
            if(!ArrayOfBall[c][r].ismine){
                ArrayOfBall[c][r].ismine=true;
                nMine++;
            }
        }
    }
    private void createMineField(){
        int c,r;
        Random ran=new Random();
        while(nMine<10)
        {
            c=ran.nextInt(9);
            r=ran.nextInt(9);
            if(!ArrayOfBall[c][r].ismine&&last_i!=c&&last_j!=r){
                ArrayOfBall[c][r].ismine=true;
                nMine++;
            }
        }
        createdMineField=true;
    }
    private void CountNoMine(int last_i,int last_j){

        int r1=last_i==0?0:-1;
        int c1=last_j==0?0:-1;
        int r2=last_i==8?1:2;
        int c2=last_j==8?1:2;
        for(;r1<r2;r1++)
            for(int j=c1;j<c2;j++)
            {
                if(ArrayOfBall[last_i+r1][last_j+j].ismine) nMineAround++;
            }
    }
    private void openField(int last_i,int last_j)
    {
            if(!ArrayOfBall[last_i][last_j].ismine)
                 {
                    CountNoMine(last_i,last_j);
                     if(nMineAround==0)
                     {
                       /*  int r1=last_i==0?0:-1;
                         int c1=last_j==0?0:-1;
                          int r2=last_i==8?1:2;
                         int c2=last_j==8?1:2;
                         for(;r1<r2;r1++)
                        for(int j=c1;j<c2;j++)
                        {
                             openField(last_i+r1,last_j+j);
                         }*/
                         ArrayOfBall[last_i][last_j].ishide = true;
                     }
                     else
                     {

                         ArrayOfBall[last_i][last_j].setNoMineAround(nMineAround);
                         nMineAround=0;
                     }
                 }
    }
    private void loadGraphics() {// can thiet
        try {
            ImageLoader loader = ImageLoader.getInstance();
            balls=loader.loadImage("/balls.png");
          /*  balls = new Sprite(loader.loadImage("/balls.png"), 25, 25);
            balls.setRefPixelPosition(25, 25);
          //  balls.setPosition(carXPosition, carYPosition);
            balls.setFrame(currentFrame);
           */
            countDown = new Sprite(loader.loadImage("/countdown_240x121.png"), 240, 121);
            countDown.setPosition(0, 100);
            countDown.setFrame(0);
           
            startInfo = loader.loadImage("/press_info.png");
            bg=loader.loadImage("/bkg.png");


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   

    public void showNotify() {
        
        
        //////////// Doạn này nên giữ lại
        mTimer = new Timer();
        g = getGraphics();
        TimerTask ui = new TimerTask() { // phụ trách vẽ

            public void run() {
                render(g);
                flushGraphics();
            }
        };
        gameLogic = new SimpleThread(40) { // phụ trách tính toán trong game

            public void execute() {
                if (!stopped) {
                   


                }
            }
        };
        ///////////
      
       
        gameLogic.start();
       
        mTimer.schedule(ui, 0, 40);

  
         
       

        countdownThread = new Thread() {
            public void run() {
                try {
                    countDown.setFrame(0);
                    pauseCounter = 1;
                    Thread.sleep(1000);
                    countDown.nextFrame();
                    pauseCounter = 2;
                    Thread.sleep(1000);
                    countDown.nextFrame();
                    pauseCounter = 3;
                    Thread.sleep(1000);
                    countDown.nextFrame();
                    Thread.sleep(700);
                    stopped = false;
                  //  raceTimer.scheduleAtFixedRate(clock, 10, 10);
                } catch (InterruptedException ie) {
                }
            }
        };
        countdownThread.start();
       
    }

    protected void hideNotify() {
         mTimer.cancel();
         countdownThread.interrupt();
    /*    mTimer.cancel();
        raceTimer.cancel();        
        gateKeeper.stop();
        gameLogic.stop();
        engine.off();
        stopped = true;*/
    }
    public void reset() {
   
    }

    private void render(Graphics g) {
        int anchor = g.TOP | g.LEFT;
        
        g.setColor(0xFFFFFF);
        g.fillRect(0, 0, getWidth(), getHeight());
      //  balls.setPosition(carXPosition, carYPosition);
        g.drawImage(bg, 0, 0, anchor);
       
       for(int i=0;i<9;i++)
            for(int j=0;j<9;j++)
            {
                ArrayOfBall[i][j].render(g);
            }
        if (stopped) {
            g.drawImage(startInfo, 0, 66, anchor);
            countDown.paint(g);
        }

        if(p!=null) p.render(g);
        //drawDebugData(g);
    }

    
   

   



 protected void pointerPressed(int x, int y) {
        for(int i=0;i<9;i++)
            for(int j=0;j<9;j++)
            {
                if(i!=last_i||j!=last_j)
                if(ArrayOfBall[i][j].OnSelelected(x, y))
                {
                  if(last_i!=-1) ArrayOfBall[last_i][last_j].reset();
                  last_i=i;
                  last_j=j;
                  i=9;
                  break;
                }
            }
            p=null;
    }

    protected void pointerReleased(int x, int y) {
       /* for(int i=0;i<9;i++)
            for(int j=0;j<9;j++)
            {
                if(ArrayOfBall[i][j].OnSelelected(x, y));
            }*/
    }
    
    protected void keyPressed(int keyCode) {
        if(p==null) // khởi tạo vị trí cho con trỏ
        {
            if(last_i==-1) // nếu chưa chọn bất kì quả trứng nào
            {
                last_i=4;
                last_j=4;
            }
            // đã chọn 1 quả trứng
            p = new Pointer(ArrayOfBall[last_i][last_j].getX(), ArrayOfBall[last_i][last_j].getY());
        }
        switch (keyCode) {
            case GameCanvas.KEY_NUM2:{ // di chuyển con trỏ lên
                ArrayOfBall[last_i][last_j].istouched=false; // bỏ chọn quả trứng hiện tại
                last_j--;
               if(last_j<0) last_j=0;
               else
               {
                   p.Up();
               }
               ArrayOfBall[last_i][last_j].OnSelected();
            }
                break;
            case GameCanvas.KEY_NUM4:{
                ArrayOfBall[last_i][last_j].istouched=false;
                last_i--;
               if(last_i<0) last_i=0;
               else
               {
                   p.Left();
               }
               ArrayOfBall[last_i][last_j].OnSelected();
            }
                break;
            case GameCanvas.KEY_NUM6:{
                ArrayOfBall[last_i][last_j].istouched=false;
                last_i++;
               if(last_i>8) last_i=8;
               else
               {
                   p.Right();
               }
               ArrayOfBall[last_i][last_j].OnSelected();
            }
                break;
             case GameCanvas.KEY_NUM8:{
                 ArrayOfBall[last_i][last_j].istouched=false;
                last_j++;
               if(last_j>8) last_j=8;
               else
               {
                   p.Down();
               }
               ArrayOfBall[last_i][last_j].OnSelected();
             }
                break;
            case GameCanvas.KEY_NUM1:{
            }
                break;
            case GameCanvas.KEY_NUM3:{
            }
                break;
             case GameCanvas.KEY_NUM5:{
                 if(!createdMineField) 
                 {
                     createMineField();
                 }

             }
                break;
        }
    }

    protected void keyReleased(int keyCode) {
        switch (keyCode) {
            case GameCanvas.KEY_NUM2:{
               
               
            }
                break;
            case GameCanvas.KEY_NUM4:{
            }
                break;
            case GameCanvas.KEY_NUM6:{
            }
                break;
             case GameCanvas.KEY_NUM8:{
             }
                break;
            case GameCanvas.KEY_NUM1:{
            }
                break;
            case GameCanvas.KEY_NUM3:{
            }
                break;
             case GameCanvas.KEY_NUM5:{
                 openField(last_i,last_j);
             }
                break;
        }
    }

   

  
   
}
